﻿using SkiaSharp;
using System;
using System.IO;

namespace YFurion.Utils
{
    public sealed class VierificationCodeUtils
    {
        /// <summary>  
        /// 该方法是将生成的随机数写入图像文件  
        /// </summary>  
        /// <param name="code">code是一个随机数</param>
        /// <param name="numbers">生成位数（默认4位）</param>  
        public static byte[] Create(out string code, int numbers = 4)
        {
            code = RndNum(numbers);
            Random random = new();
            //验证码颜色集合  
            SKColor[] colors = new[] { SKColors.Black, SKColors.Red, SKColors.DarkBlue, SKColors.Green, SKColors.Orange, SKColors.Brown, SKColors.DarkCyan, SKColors.Purple };
            //验证码背景颜色集合  
            SKColor[] backcolors = new[] { SKColors.AntiqueWhite, SKColors.WhiteSmoke, SKColors.FloralWhite };
            //验证码字体集合
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial" };
            //相当于js的 canvas.getContext('2d')
            using SKBitmap image2d = new SKBitmap(72, 32, SKColorType.Bgra8888, SKAlphaType.Premul);
            //相当于前端的canvas
            using SKCanvas canvas = new SKCanvas(image2d);
            //填充白色背景
            canvas.DrawColor(backcolors[random.Next(0, backcolors.Length - 1)]);
            //样式 跟xaml差不多
            using SKPaint drawStyle = new SKPaint();
            //填充验证码到图片
            for (int i = 0; i < code.Length; i++)
            {
                drawStyle.IsAntialias = true;
                drawStyle.TextSize = 15;
                SKTypeface font = SKTypeface.FromFamilyName(fonts[random.Next(0, fonts.Length - 1)], SKFontStyleWeight.SemiBold, SKFontStyleWidth.ExtraCondensed, SKFontStyleSlant.Upright);
                drawStyle.Typeface = font;
                drawStyle.Color = colors[random.Next(0, colors.Length - 1)];
                //写字
                canvas.DrawText(code[i].ToString(), (i + 1) * 13.5f, 20, drawStyle);
            }
            //生成6条干扰线
            for (int i = 0; i < 6; i++)
            {
                drawStyle.Color = colors[random.Next(colors.Length)];
                drawStyle.StrokeWidth = 1;
                canvas.DrawLine(random.Next(0, code.Length * 15), random.Next(0, 60), random.Next(0, code.Length * 16), random.Next(0, 30), drawStyle);
            }
            //巴拉巴拉的就行了
            using SKImage img = SKImage.FromBitmap(image2d);
            using SKData p = img.Encode(SKEncodedImageFormat.Png, 100);
            using MemoryStream ms = new MemoryStream();
            //保存到流
            p.SaveTo(ms);

            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            return arr;
        }

        /// <summary>  
        /// 该方法用于生成指定位数的随机数  
        /// </summary>  
        /// <param name="VcodeNum">参数是随机数的位数</param>  
        /// <returns>返回一个随机数字符串</returns>  
        public static string RndNum(int vcodeNum)
        {
            //验证码可以显示的字符集合  
            string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p" +
                ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q" +
                ",R,S,T,U,V,W,X,Y,Z";
            string[] VcArray = Vchar.Split(new char[] { ',' });//拆分成数组   
            string code = "";//产生的随机数  
            int temp = -1;//记录上次随机数值，尽量避避免生产几个一样的随机数  

            Random rand = new();
            //采用一个简单的算法以保证生成随机数的不同  
            for (int i = 1; i < vcodeNum + 1; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * unchecked((int)DateTimeOffset.Now.Ticks));//初始化随机类  
                }
                int t = rand.Next(61);//获取随机数  
                if (temp != -1 && temp == t)
                {
                    return RndNum(vcodeNum);//如果获取的随机数重复，则递归调用  
                }
                temp = t;//把本次产生的随机数记录起来  
                code += VcArray[t];//随机数的位数加一  
            }
            return code;
        }
    }
}
